<?php
//$Id: cache.php 452 2012-07-02 05:48:24Z tomqin@gmail.com $

/**
 * The Cache Class
 *
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

final Class Cache
{
    /**
     * Get a cache data
     *
     * @param string
     * @param integer
     * @return mixed
     */
    public static function get($name, $cache_time = 0) {
        static $cache = array();

        $key = md5(strtolower($name));
        if(!isset($cache[$key])){
            $cache[$key] = self::_getCache($key, $cache_time);
        }
        return $cache[$key];
    }

    public static function set($name, $data) {
        $key = md5(strtolower($name));
        $file = self::_cacheFile($key);
        $dir  = dirname($file);
        if(!is_dir($dir))
            mkdir($dir, 0777, true);
        return file_put_contents($file, serialize($data));
    }

    public static function del($name) {
        $key = md5(strtolower($name));
        $file = self::_cacheFile($key);
        unlink($file);
    }

    private static function _getCache($key, $cache_time = 0) {
        $file = self::_cacheFile($key);
        if(!is_file($file)){
            return null;
        }
        if($cache_time && TIMESTAMP - filemtime($file) > $cache_time) {
            return null;
        }else{
            if(is_file($file)){
                return unserialize(file_get_contents($file));
            }else{
                return null;
            }
        }
    }

    private static function _cacheFile($key){
        return SYSTEM_ROOT . 'data' .DS. 'cache' .DS. $key{0} .DS. $key{1} .DS. $key{2} .DS. $key.'.dat';
    }
}
?>